package com.yc.fav.util;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.core.io.ClassPathResource;

public class MybatisHelper {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            ClassPathResource d = new ClassPathResource("mybatis-plus.xml");
            MybatisSqlSessionFactoryBean sqlSessionFactoryBean =
                    new MybatisSqlSessionFactoryBean();
            sqlSessionFactoryBean.setConfigLocation(d);
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/C118-S3-Ply-fav");
            dataSource.setUsername("root");
            dataSource.setPassword("12345");
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactory = sqlSessionFactoryBean.getObject();
        } catch (Throwable e) {
            throw new RuntimeException("mybatis-plus 初始化失败！", e);
        }
    }

    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}
